<script>
// 注意：模块化不允许这样引入 import { Select } from "element-ui";
import ElementUI from "element-ui";
const { Select } = ElementUI;

import { getValueByPath } from "element-ui/src/utils/util";
export default {
  name: "ElSelectPatch",
  extends: Select,
  watch: {
    options() {
      if (this.$isServer) return;
      this.$nextTick(() => {
        this.broadcast("ElSelectDropdown", "updatePopper");
      });
      if (this.multiple) {
        this.resetInputHeight();
      }
      // let inputs = this.$el.querySelectorAll("input");
      // if ([].indexOf.call(inputs, document.activeElement) === -1) {
      //   this.setSelected();
      // }
      // 修改代码, 解决当options未加载回来时候, 点击下拉未匹配数据
       this.setSelected();
      if (
        this.defaultFirstOption &&
        (this.filterable || this.remote) &&
        this.filteredOptionsCount
      ) {
        this.checkDefaultFirstOption();
      }
    },
  },
  methods: {
    getOption(value) {
      let option;
      const isObject =
        Object.prototype.toString.call(value).toLowerCase() ===
        "[object object]";
      const isNull =
        Object.prototype.toString.call(value).toLowerCase() === "[object null]";
      const isUndefined =
        Object.prototype.toString.call(value).toLowerCase() ===
        "[object undefined]";

      for (let i = this.cachedOptions.length - 1; i >= 0; i--) {
        const cachedOption = this.cachedOptions[i];
        const isEqual = isObject
          ? getValueByPath(cachedOption.value, this.valueKey) ===
            getValueByPath(value, this.valueKey)
          : cachedOption.value === value;
        if (isEqual) {
          option = cachedOption;
          break;
        }
      }
      if (option) return option;
      // 修改代码, value是Object时候, 获取label-key对应的值即modelLabel
      const modelLabel = value?.[this.$attrs?.["label-key"]];
      const label = !isObject && !isNull && !isUndefined ? String(value) : modelLabel;
      let newOption = {
        value: value,
        currentLabel: label,
      };
      if (this.multiple) {
        newOption.hitState = false;
      }
      return newOption;
    },
  },
};
</script>
